package com.wu.pmo.controller;


import com.wu.pmo.dto.ProjectListDTO;
import com.wu.pmo.dto.ProjectRequestDTO;
import com.wu.pmo.entity.Projects;
import com.wu.pmo.service.ProjectsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class ProjectController {
    @Autowired
    private ProjectsService projectsService;

    //查询首页展示项目
    @GetMapping("/select")
    public ResponseEntity<List<ProjectListDTO>> getAllProjects(){
        List<ProjectListDTO> projectsList = projectsService.getProjectList();
        return ResponseEntity.ok(projectsList);
    }

    //查询项目详情
    @GetMapping("/project/{id}")
    public ResponseEntity<ProjectRequestDTO> getProjectDetails(@PathVariable Integer id) {
        ProjectRequestDTO projectDetails = projectsService.getProjectDetailsById(id);
        if (projectDetails != null) {
            return ResponseEntity.ok(projectDetails);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    //新增项目
    @PostMapping("/insert")
    public ResponseEntity<Projects> createProject(@RequestBody ProjectRequestDTO projectDto){
        Projects newProject = projectsService.createProject(projectDto);
        return ResponseEntity.ok(newProject);
    }
    //修改项目
    @PostMapping("/update")
    public ResponseEntity<Projects> updateProject(@RequestBody ProjectRequestDTO projectDto) {
        try {
            Projects updatedProject = projectsService.updateProject(projectDto);
            return ResponseEntity.ok(updatedProject);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.notFound().build();
        }
    }

    //删除项目
    @PostMapping("/delete")
    public ResponseEntity<Void> deleteProject(@RequestBody Map<String, Object> payload) {
        Integer id = (Integer) payload.get("id");
        String type = (String) payload.get("type");

        if ("physical".equals(type)) {
            projectsService.physicalDeleteProject(id);
        } else {
            projectsService.logicalDeleteProject(id);
        }
        
        return ResponseEntity.ok().build();
    }
}
